package com.lovo.aspect;

import com.lovo.enums.UserCodeEnum;
import com.lovo.exception.MyException;
import com.lovo.utils.ResultFactory;
import com.lovo.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @title  全局异常控制
 * @author: luo
 * @date: 2020/11/17 20:22
 */
/**控制器切面*/
@RestControllerAdvice
@Slf4j
public class GlobalHandleException {

    /**
     * 自定义异常处理
     * @param e 自定义异常
     * @return 错误信息
     */
    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVO handleUserException(MyException e){
        log.error(e.getMessage());
        return ResultFactory.fail(e.getUserCodeEnum());
    }

    /**
     * 参数异常处理
     * @param e 参数异常
     * @return 错误信息
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error(e.getMessage());
        return ResultFactory.fail(UserCodeEnum.PARAMETER_FORMAT_ERROR);
    }

    /**
     * 请求方式异常处理
     * @param e 请求方式异常
     * @return 错误信息
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVO handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        log.error(e.getMessage());
        return ResultFactory.fail(UserCodeEnum.HTTP_REQUEST_METHOD_NOT_SUPPORTED);
    }

    /**
     * 其他异常处理
     * @param e 其他异常
     * @return 错误信息
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e){
        log.error(e.getMessage());
        return ResultFactory.fail(UserCodeEnum.UNKNOWN_FAIL);
    }


}
